package org.jjliu.example.dao;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import freemarker.cache.ClassTemplateLoader;
import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;

public class TempParser {
	static Configuration configuration;
	static{
		configuration = new Configuration();
        configuration.setObjectWrapper(new DefaultObjectWrapper());
        configuration.setTemplateLoader(new ClassTemplateLoader());
	}
	
	String path;
	Map<String, Object> params;
	
	public TempParser(String path) {
		this.path = path;
		params = new TreeMap<String, Object>();
	}
	
	public TempParser addParam(String key,Object value){
		params.put(key, value);
		return this;
	}
	
	public TempParser addParams(Map<String,Object>params){
		this.params.putAll(params);
		return this;
	}
		
	public String parse(){
		String res;
		try {
			Template temp = configuration.getTemplate(path);
			StringWriter writer = new StringWriter();
			temp.process(params, writer);
			res = writer.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return res;
	}
}
